package com.mapreduce;

import com.bean.AvgTemp;
import org.apache.hadoop.conf.Configuration;
import org.apache.hadoop.conf.Configured;
import org.apache.hadoop.fs.FileSystem;
import org.apache.hadoop.fs.Path;
import org.apache.hadoop.io.DoubleWritable;
import org.apache.hadoop.io.Text;
import org.apache.hadoop.mapreduce.Job;
import org.apache.hadoop.mapreduce.Mapper;
import org.apache.hadoop.mapreduce.lib.input.SequenceFileInputFormat;
import org.apache.hadoop.mapreduce.lib.output.TextOutputFormat;
import org.apache.hadoop.util.Tool;

import java.io.IOException;
import java.net.URI;

public class JobAvg extends Configured implements Tool {
    static class JobAvgMapper extends
            Mapper<Text, AvgTemp, Text, DoubleWritable>{
        @Override
        protected void map(Text key, AvgTemp value, Mapper<Text, AvgTemp, Text, DoubleWritable>.Context context) throws IOException, InterruptedException {
            double avg = (double) value.getSum() / value.getNum();
            context.write(key,new DoubleWritable(avg));
        }
    }
    @Override
    public int run(String[] args) throws Exception {
        Configuration conf = getConf();

        // 指定输入输出路径
        Path output1 = new Path(
                "hdfs://192.168.10.11:9000/snoutput");
        Path output2 = new Path(
                "hdfs://192.168.10.11:9000/avgoutput");

        FileSystem fs = FileSystem.get(
                new URI("hdfs://192.168.10.11:9000")
                ,conf);
        if (fs.exists(output2)) fs.delete(output2,true);
        //构建Job
        Job job2 = Job.getInstance(conf);
        job2.setJobName("avg");
        job2.setJarByClass(this.getClass());
        // 指定map类的配置
        job2.setMapperClass(JobAvgMapper.class);
        job2.setMapOutputKeyClass(Text.class);
        job2.setMapOutputValueClass(DoubleWritable.class);

        job2.setNumReduceTasks(0);

        job2.setInputFormatClass(SequenceFileInputFormat.class);
        SequenceFileInputFormat.addInputPath(job2,output1);

        TextOutputFormat.setOutputPath(job2,output2);

        return job2.waitForCompletion(true)?0:-1;
    }
}
